package lzy.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/data")
    public String getData() {
        return "Protected data";
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/hello")
    public String hello() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return "No authenticated user found.";
        }

        Object principal = authentication.getPrincipal();
        String username = "";
        Collection<? extends GrantedAuthority> authorities = null;

        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
            authorities = userDetails.getAuthorities();
        } else if (principal instanceof String) {
            username = (String) principal;
        }

        StringBuilder roles = new StringBuilder("User: ").append(username).append(", Roles: ");
        if (authorities != null) {
            for (GrantedAuthority authority : authorities) {
                roles.append(authority.getAuthority()).append(" ");
            }
        }

        return roles.toString();
    }
}
